<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ruby data types</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Ruby, learn Ruby, data types, tutorial, programming language">
<meta name="description" content="In this part of the Ruby tutorial, we cover data types.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content2">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Ruby data types</h1>

<p>
In this part of the Ruby tutorial, we will talk about data types. 
</p>

<p>
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients.
Tools to work with various data types are essential part of a modern computer language. 
A <b>data type</b> is a set of values, and the allowable operations on 
those values.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<p>
Ruby has several data types. All data types are based on classes.
The following are the data types recognized in Ruby:
</p>

<ul>
<li>Booleans</li>
<li>Symbols</li>
<li>Numbers</li>
<li>Strings</li>
<li>Arrays</li>
<li>Hashes</li>
</ul>

<p>
In the following example, we have all important Ruby
data types.
</p>

<pre class="code">
#!/usr/bin/ruby

h = { :name => "Jane", :age => 17 }

p true.class, false.class
p "Ruby".class
p 1.class
p 4.5.class
p 3_463_456_457.class
p :age.class
p [1, 2, 3].class
p h.class
</pre>

<p>
We print their class names. A class is a template from each 
object is created.  
</p>

<pre class="explanation">
p true.class, false.class
</pre>

<p>
The boolean values are presented by true and false objects.
</p>

<pre class="explanation">
p "Ruby".class
</pre>

<p>
This is the string.
</p>

<pre class="explanation">
p 1.class
p 4.5.class
p 3_463_456_457.class
</pre>

<p>
These are the numbers. 
</p>

<pre class="explanation">
p :age.class
</pre>

<p>
This is a symbol, a data type specific to Ruby.
</p>

<pre class="explanation">
p [1, 2, 3].class
p h.class
</pre>

<p>
These are two containers, the array and the hash.
</p>

<pre>
$ ./types.rb
TrueClass
FalseClass
String
Fixnum
Float
Bignum
Symbol
Array
Hash
</pre>

<p>
The program lists classes that belong to Ruby data
types.
</p>



<h2>Boolean values</h2>

<p>
There is a duality built in our world. There is a Heaven and Earth, water and fire, 
jing and jang, man and woman, love and hatred. This is the 'boolean' nature of our
existence. In Ruby the boolean data type can have one of the two values: true or false. 
It is a fundamental data type. Very common in computer programs.
</p>

<p>
Happy parents are waiting a child to be born. They have chosen a name for both
possibilities. If it is going to be a boy, they have chosen John. If it is
going to be a girl, they have chosen Victoria. 
</p>

<pre class="code">
#!/usr/bin/ruby

# kid.rb

bool = [true, false]

male = bool[rand(2)]


if male
    puts "We will use name John"
else 
    puts "We will use name Victoria"
end
</pre>

<p>
The program uses a random number generator to simulate our case. 
</p>

<pre class="explanation">
bool = [true, false]
</pre>

<p>
We have a bool variable. It is an array of two boolean values. 
An array is created with square brackets. 
</p>

<pre class="explanation">
male = bool[rand(2)]
</pre>

<p>
We use a <code>rand()</code> method to create a random number. The
method returns either 0 or 1. The returned number is an index to the
bool array. 
</p>

<pre class="explanation">
if male
    puts "We will use name John"
else 
    puts "We will use name Victoria"
end
</pre>

<p>
Depending on the male variable, we print a message. 
If the male variable is set to true, we choose name John.
Otherwise, we choose name Victoria. Control structures like
if/else statements work with boolean values. 
</p>


<pre>
$ ./kid.rb 
We will use name Victoria
$ ./kid.rb 
We will use name Victoria
$ ./kid.rb 
We will use name John
$ ./kid.rb 
We will use name John
$ ./kid.rb 
We will use name John
</pre>

<p>
Running the program several times. 
</p>


<h2>Symbols</h2>

<p>
Symbols are used to represent other objects. 
Using symbols instead of strings may save some resources.
A symbol is an instance object of a <code>Symbol</code> class. 
Symbols are generated by using an colon before an identifier, like :name. 
Several objects also have <code>to_sym</code> methods, that convert them
to symbols. 
</p>

<p>
A Ruby symbol cannot be changed at runtime. Ruby symbols
are often used as hash keys, because we do not need full
capabilities of a string objects for a key.
</p>

<pre class="code">
#!/usr/bin/ruby

p :name
p :name.class
p :name.methods.size
p "Jane".methods.size

p :name.object_id
p :name.object_id
p "name".object_id
p "name".object_id
</pre>

<p>
In the first example, we show some basic operations with Ruby symbols.
</p>

<pre class="explanation">
p :name
p :name.class
</pre>

<p>
We print a symbol and its class to the console. The class of the symbol
is <code>Symbol</code>.
</p>

<pre class="explanation">
p :name.methods.size
p "Jane".methods.size
</pre>

<p>
We compare the amount of methods that has a symbol and a string. 
A string has more than twice as many methods than symbol. 
</p>

<pre class="explanation">
p :name.object_id
p :name.object_id
p "name".object_id
p "name".object_id
</pre>

<p>
Same symbols have same id. Same strings have different ids. 
</p>

<pre>
$ ./symbols.rb
:name
Symbol
79
162
10328
10328
77344750
77344730
</pre>

<p>
Sample output.
</p>

<hr class="btm">

<p>
Symbols may be used as flags. Constants may be used in such situations
as well. In C/C++ we would use enumerations. 
</p>

<pre class="code">
#!/usr/bin/ruby

light = :on

if light == :on
    puts "The light is on"
else
    puts "The light is off"
end

light = :off

if light == :on
    puts "The light is on"
else
    puts "The light is off"
end
</pre>

<p>
A light may be in two states. On and off. For both states
we might define symbols. 
</p>

<pre class="explanation">
light = :on
</pre>

<p>
The light is on. 
</p>

<pre class="explanation">
if light == :on
    puts "The light is on"
else
    puts "The light is off"
end
</pre>

<p>
The logic of the program depends on the state of the
light variable. 
</p>

<hr class="btm">

<p>
Symbols are often used as keys in hash containers. They
are more efficient that strings. 
</p>

<pre class="code">
#!/usr/bin/ruby

domains = {:sk => "Slovakia", :no => "Norway", :hu => "Hungary"}

puts domains[:sk]
puts domains[:no]
puts domains[:hu]
</pre>

<p>
In the script we have a domains hash. The keys in the hash
are symbols. 
</p>

<pre class="explanation">
puts domains[:sk]
puts domains[:no]
puts domains[:hu]
</pre>

<p>
Keys are used to access values of a hash. Here we print three
values of a hash. 
</p>

<pre>
$ ./symbols3.rb
Slovakia
Norway
Hungary
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
Ruby interpreter stores some refererences internally as symbols. 
</p>

<pre class="code">
#!/usr/bin/ruby

class Being
    
    def initialize
        @is = true
    end
    
    def say
        "I am being"
    end
end

b = Being.new

p b.method :say
p b.instance_variable_get :@is
</pre>

<p>
A Being class is defined. The class has a custom instance variable
@is and a say method. These two entities are stored using symbols by
Ruby.
</p>

<pre class="explanation">
p b.method :say
</pre>

<p>
The <code>method</code> method looks up a receiver method with 
a given name in the b object. We look for a :say symbol. 
</p>

<pre class="explanation">
p b.instance_variable_get :@is
</pre>

<p>
We check with a <code>instance_variable_get</code> method, if
the @is variable is an instance variable of the b object. 
Internally the variable is stored as a :@is symbol. 
</p>

<pre>
$ ./symbols4.rb 
#&lt;Method: Being#say&gt;
true
</pre>

<p>
Generated output.
</p>

<hr class="btm">

<p>
All symbols are stored in a symbol table. In the next
example, we look at the table. The <code>all_symbols</code>
method of a <code>Symbol</code> class returns a array
of all symbols from the table. 
</p>

<pre class="code">
#!/usr/bin/ruby

def info
  "info method"
end

@v = "Ruby"
@@n = "16"

p Symbol.all_symbols.include? :info
p Symbol.all_symbols.include? :@v
p Symbol.all_symbols.include? :@@n
</pre>

<p>
A method, an instance variable and a class variable are
created in a Ruby script. We check, if these entities are
stored in a symbol table. 
</p>

<pre class="explanation">
p Symbol.all_symbols.include? :info
</pre>

<p>
We check, if the :info symbol is in the symbol table. The
line returns true. 
</p>

<pre>
$ ./symbols5.rb
true
true
true
</pre>

<p>
All three symbols are present in the Ruby symbol table.
</p>


<h2>Integers</h2>

<p>
Integers are a subset of the real numbers. They are written without 
a fraction or a decimal component. Integers fall within a set
Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite. 
</p>

<p>
In computer languages, integers are primitive data types. Computers can 
practically work only with a subset of integer values, because computers
have finite capacity. Integers are used to count discrete entities. We 
can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can 
have 3.33 kilograms.
</p>

<p>
Integers are instance objects of a <code>Fixnum</code> or a <code>Bignum</code>
class in Ruby. Unlike in languages like Java or C, integers in Ruby are objects.
The two classes differ in size. Fixnum numbers are integers up to a certain
limit. The limite is machine dependent. Bignum values hold integers outside
the range of the Fixnum. If any operation on a Fixnum exceeds its range, 
the value is automatically converted to a Bignum. The programmer usually
does not need to care about the class type of the integers.
</p>

<pre class="code">
#!/usr/bin/ruby

p -2
p 121
p 123265
p -34253464356
p 34867367893463476

p 1.class
p 23453246.class
p 234532423563456346.class
p 2345324235632363463456456346.class

p 5 / 2
p 5.div 2
</pre>

<p>
In this example, we deal with integers. 
</p>

<pre class="explanation">
p -2
p 121
p 123265
p -34253464356
p 34867367893463476
</pre>

<p>
These are integer values of various size. Both positive and
negative values.
</p>

<pre class="explanation">
p 1.class
p 23453246.class
p 234532423563456346.class
p 2345324235632363463456456346.class
</pre>

<p>
We print the classes of these integers. The first two integer
are instances of a <code>Fixnum</code> class, the other two
are instances of a <code>Bignum</code> class.
</p>

<pre class="explanation">
p 5 / 2
p 5.div 2
</pre>

<p>
The two lines show the integer division. When we divide two integers
using the integer division operator/method, the result is 
an integer as well.
</p>

<pre>
$ ./integers.rb
-2
121
123265
-34253464356
34867367893463476
Fixnum
Fixnum
Bignum
Bignum
2
2
</pre>

<p>
Output of the example.
</p>

<hr class="btm">

<p>
Integers can be specified in different <b>notations</b> in 
Ruby. Decimal, hexadecimal, octal and binary. Decimal numbers are used normally, 
as we know them. Hexadecimal numbers are preceded with 0x characters, octal with
0 character and binary with 0b characters. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts 122
puts 0x7a
puts 0172
puts 0b1111010
</pre>

<p>
In the code example, we print decimal 122 in all these notation. 
</p>

<pre>
$ ./inotations.rb
122
122
122
122
</pre>

<p>
Ouput of the example. 
</p>

<hr class="btm">

<p>
If we work with integers, we deal with discrete 
entities. We would use integers to count apples. 
</p>

<pre class="code">
#!/usr/bin/ruby

baskets = 16
apples_in_basket = 24

total = baskets * apples_in_basket

puts "There are total of #{total} apples"
</pre>


<p>
In our program, we count the total amount of apples. We work
with integers. 
</p>

<pre>
$ ./apples.rb
There are total of 384 apples
</pre>

<p>
The output of the program. 
</p>

<hr class="btm">

<p>
Big numbers are difficult to read. If we have a number like 
245342395423452, we find it difficult to read quickly. Outside
computers, big numbers are separated by spaces or commas. Ruby
allows to separate integers with an underscore, which is simply
ignored by the Ruby interpreter. 
</p>

<pre class="code">
#!/usr/bin/ruby

p 23482345629
p 23_482_345_629

p 23482345629 == 23_482_345_629
</pre>

<p>
In the example, we demonstrate the usage of the underscores.
</p>

<pre class="explanation">
p 23482345629 == 23_482_345_629
</pre>

<p>
This line shows that the two numbers are equal. 
It prints true.
</p>

<pre>
$ ./underscore.rb
23482345629
23482345629
true
</pre>

<p>
Example output.
</p>


<h2>Floating point numbers</h2>

<p>
Floating point numbers represent real numbers in computing. Real numbers 
measure continuous quantities. Like weight, height or speed. In Ruby, 
decimal numbers are objects of the <code>Float</code> 
or a <code>BigDecimal</code> class. The <code>BigDecimal</code> class
is part of the standard library, it is a Ruby core class. 
In addition, we can use <code>Rational</code> objects too. 
</p>

<p>
We need to understand that decimal numbers are not precise. The 
official Ruby documentation says it clearly, Float objects represent 
inexact real numbers. 
</p>

<pre class="code">
#!/usr/bin/ruby

p 15.4
p 0.3455
p -343.4563

p 12.5.class
p -12.5.class
p (5.0 / 2).class

p 5.fdiv 2
p 12.to_f
</pre>

<p>
In the above program, we work with floating point values. 
</p>

<pre class="explanation">
p 15.4
p 0.3455
p -343.4563
</pre>

<p>
Here we print three decimal values. Decimal numbers have a 
decimal point character. 
</p>

<pre class="explanation">
p 12.5.class
p -12.5.class
p (5.0 / 2).class
</pre>

<p>
The above code lines show the types of the numbers. All are floats. 
Integer division applied on at least one <code>Float</code> produces 
a <code>Float</code> too. 
</p>

<pre class="explanation">
p 5.fdiv 2
p 12.to_f
</pre>

<p>
Here we create floating point values by using the floating point <code>fdiv</code>
division method and the conversion <code>to_f</code> method. 
</p>

<pre>
$ ./decimals.rb
15.4
0.3455
-343.4563
Float
Float
Float
2.5
12.0
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
By default, a decimal number is shown with a maximum 16 numbers
after the decimal point. We can control the format
of floating point values with the <code>sprintf</code>
or <code>printf</code> methods. 
</p>

<pre class="code">
#!/usr/bin/ruby

p 1/3.0
p 1.fdiv 2

puts sprintf "%.4f" % (1/3.0)
puts sprintf "%.7f" % (5/3.0)
</pre>

<p>
Formatting decimal numbers. 
</p>

<pre class="explanation">
p 1/3.0
p 13.fdiv 4
p 1.fdiv 2
</pre>

<p>
The first line prints a decimal with 16 places after
the point. The second line prints two numbers after the
point and the third one. 
</p>

<pre class="explanation">
puts sprintf "%.4f" % (1/3.0)
puts sprintf "%.7f" % (5/3.0)
</pre>

<p>
Here we control the number of values after the
decimal point using the <code>sprintf</code> method.
There is a precision in the format specifier
of the <code>sprintf</code> method. It is a number following
the % character. The f is a conversion specifier that says
we are dealing with floating point values.
</p>


<pre>
$ ./formatfloat.rb
0.3333333333333333
3.25
0.5
0.3333
1.6666667
</pre>

<p>
Output.
</p>

<hr class="btm">


<p>
Ruby supports the scientific syntax of the floating point
values. Also known as exponential notation, it is a way of writing numbers
too large or small to be conveniently written in standard decimal 
notation.
</p>

<pre class="code">
#!/usr/bin/ruby

p 1.2e-3
p 0.0012

p 1.5E-4
p 0.00015
</pre>

<p>
The example shows two decimal numbers written in scientific notation.
</p>


<pre>
$ ./scientific.rb
0.0012
0.0012
0.00015
0.00015
</pre>

<p>
This is the output of the above program. 
</p>

<hr class="btm">

<p>
As we have already stated, floating point values are slightly
inaccurate. In many situations this precision is sufficient. It is
not that important, if our weight is 60kg or 60.000023kg. 
On the other hand, there are computations in which the 
precision is paramount. Especially in science or
engineering.  
</p>

<p>
Ruby has a <code>BigDecimal</code> in the standard library. This
class provides arbitrary precision for very large or very accurate 
floating point numbers.
</p>

<pre class="code">
#!/usr/bin/ruby

require 'bigdecimal'

sum = 0

1000.times do
    sum = sum + 0.0001
end

p sum


sum = BigDecimal.new("0")

1000.times do
    sum = sum + BigDecimal.new("0.0001")
end

puts sum.to_s('F')
puts sum.to_s('E')
</pre>

<p>
In this simple example, we compare the precision of a 
<code>Float</code> compared to a <code>BigDecimal</code>.
</p>

<pre class="explanation">
require 'bigdecimal'
</pre>

<p>
The <code>BigDecimal</code> class must be imported. 
</p>

<pre class="explanation">
sum = 0

1000.times do
    sum = sum + 0.0001
end

p sum
</pre>

<p>
We form a loop, where we add a small floatig point value
to a sum variable. In the end, there will be a small inaccuracy.
</p>

<pre class="explanation">
sum = BigDecimal.new("0")

1000.times do
    sum = sum + BigDecimal.new("0.0001")
end
</pre>

<p>
We do the same loop with the <code>BigDecimal</code> values.
</p>

<pre class="explanation">
puts sum.to_s('F')
puts sum.to_s('E')
</pre>

<p>
The sum is printed in floting point and engineering notation.
</p>

<pre>
$ ./bigdecimal.rb
0.10000000000000184
0.1
0.1E0
</pre>

<p>
The output shows that the computing with <code>BigDecimal</code> is more
precise than with <code>Floats</code>. 
</p>

<hr class="btm">

<p>
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
</p>

<pre class="code">
#!/usr/bin/ruby

distance = 0.1
time = 9.87 / 3600

speed = distance / time

puts "The average speed of a sprinter is #{speed} km/h"
</pre>

<p>
In this example, it is necessary to use floating point values. 
</p>

<pre class="explanation">
distance = 0.1
</pre>

<p>
100m is 0.1 km.
</p>

<pre class="explanation">
time = 9.87 / 3600
</pre>

<p>
9.87s is 9.87/60*60 h
</p>


<pre class="explanation">
speed = distance / time
</pre>

<p>
To get the speed, we divide the distance by the time. 
</p>


<pre>
$ ./speed.rb
The average speed of a sprinter is 36.4741641337386 km/h
</pre>

<p>
This is the output of the speed.rb script.
</p>


<h2>Rational Numbers</h2>

<p>
Ruby supports rational numbers. A rational number is an exact
number. Using rational numbers we avoid rounding errors. 
In Ruby, a rational number is an object of the <code>Rational</code>
class. We can create rational numbers with a special <code>to_r</code>
method from some objects. 
</p>

<p>
A rational number is any number that can be expressed as a fraction
of two integers a/b , where b!=0. Since b may be equal to 1, every
integer is a rational number. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts 2.to_r
puts "23".to_r
puts 2.6.to_r

p Rational 0
p Rational 1/5.0
p Rational 0.5
</pre>

<p>
This example shows a few rational numbers. 
</p>

<pre class="explanation">
puts 2.to_r
</pre>

<p>
Here we convert a 2 integer to 2/1 rational number using the 
<code>to_r</code> method.
</p>

<pre class="explanation">
p Rational 0.5
</pre>

<p>
We create a rational number with the <code>Rational</code> class.
</p>

<pre>
$ ./rational.rb
2/1
23/1
5854679515581645/2251799813685248
(0/1)
(3602879701896397/18014398509481984)
(1/2)
</pre>

<p>
Output of the example.
</p>

<h2>The nil value</h2>

<p>
Ruby has a special value <code>nil</code>. It is an absence of a value.
The <code>nil</code> is a singleton object of a <code>NilClass</code>. 
There is only one <code>nil</code>; we cannot have more of it. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts nil
p nil

p $val

p [1, 2, 3][4] 

p $val1 == $val2
</pre>

<p>
An example with the <code>nil</code> value. 
</p>

<pre class="explanation">
puts nil
p nil
</pre>

<p>
We print the <code>nil</code> value to the console. The
<code>puts</code> method prints an empty string; the
<code>p</code> method prints 'nil' string. 
</p>

<pre class="explanation">
p $val
</pre>

<p>
When we refer to a global variable that was not set,
we get the <code>nil</code> value. 
</p>

<pre class="explanation">
p [1, 2, 3][3] 
</pre>

<p>
In this code line, we refer to the fourth element of
a three-element array. We get <code>nil</code>. Many methods
in Ruby return <code>nil</code> for invalid values.
</p>

<pre class="explanation">
p $val1 == $val2
</pre>

<p>
The line returns true. This is a consequence of the fact, that
the <code>nil</code> value is a singleton object of a <code>NilClass</code>.
</p>

<pre>
$ ./nilvalue.rb

nil
nil
nil
true
</pre>

<p>
Output.
</p>


<h2>Strings</h2>

<p>
A <b>string</b> is a data type representing textual data in computer programs.
A Ruby string is a sequence of unicode characters. A string is an instance of
the <code>String</code>. String literals are characters enclosed in double
or single qoutes. 
</p>

<p>
A string is a very important data type. It deserves a dedicated chapter. 
Here we just drop a small example. 
</p>

<pre class="code">
#!/usr/bin/ruby

p "Ruby"
p 'Python'

p "Ruby".size
p "Ruby".upcase

p 23.to_s
</pre>

<p>
In this program, we work with Ruby strings. We use the <code>p</code>
method for printing, because we see the data type on output. 
</p>

<pre class="explanation">
p "Ruby"
p 'Python'
</pre>

<p>
We print two string literals to the terminal. The first literal 
is enclosed in double quotes, the second literal in single quotes. 
</p>

<pre class="explanation">
p "Ruby".size
p "Ruby".upcase
</pre>

<p>
These two lines call two string methods. The <code>size</code> method
returns the size of the string. 4 characters in our case. The <code>upcase</code>
returns the string in uppercase letters. 
</p>

<pre class="explanation">
p 23.to_s
</pre>

<p>
The <code>to_s</code> method converts an integer to a string.
</p>

<pre>
$ ./strings.rb
"Ruby"
"Python"
4
"RUBY"
"23"
</pre>

<p>
In the output we see strings enclosed in quotes. This is the consequence
of using the <code>p</code> method. The <code>print</code> and <code>puts</code>
methods don't do this. 
</p>


<h2>Arrays and hashes</h2>

<p>
Arrays and hashes are collections of objects. They group objects into
one place. 
</p>

<p>
Arrays are ordered collections of objects. Hashes are collections 
of key-value pairs. We will have a single chapter for both arrays 
and hashes. The following example just gives a quick look at both
containers.
</p>


<pre class="code">
#!/usr/bin/ruby

nums = [1, 2, 3, 4]

puts "There are #{nums.size} items in the array"

nums.each do |num|
    puts num
end


domains = { :de => "Germany", :sk => "Slovakia",
            :us => "United States", :no => "Norway" }

puts domains.keys
puts domains.values
</pre>

<p>
This is a quick example for a Ruby array and hash.
</p>

<pre class="explanation">
nums = [1, 2, 3, 4]

puts "There are #{nums.size} items in the array"

nums.each do |num|
    puts num
end
</pre>

<p>
These lines create an array having 4 items. In the second
line we count the items of the array and incorporate it in
the message. Later we go through the array with the <code>each</code>
method and print each of the elements to the console. 
</p>

<pre class="explanation">
domains = { :de => "Germany", :sk => "Slovakia",
            :us => "United States", :no => "Norway" }

puts domains.keys
puts domains.values
</pre>

<p>
Here we create a Ruby hash. Then we print its keys and values.
</p>

<pre>
$ ./arrayshashes.rb
There are 4 items in the array
1
2
3
4
de
sk
us
no
Germany
Slovakia
United States
Norway
</pre>

<p>
Example output.
</p>



<h2>Conversions</h2>

<p>
We often work with multiple data types at once. Converting one data 
type to another one is a common job in programming. <b>Type conversion</b> 
or <b>typecasting</b> refers to changing an entity of one data type 
into another. There are two types of conversion. Implicit and explicit. 
Implicit type conversion, also known as coercion, is an automatic type 
conversion by the compiler. Ruby has only explicit conversion. 
</p>

<p>
Ruby has built-in conversion methods
like <code>to_i</code>, <code>to_s</code> or <code>to_f</code>. 
The <code>Kernel</code> module has a few public methods for 
doing conversions, like <code>Integer</code>, <code>String</code>
or <code>Float</code>. These methods should not be confused with
Ruby classes.
</p>

<pre class="code">
#!/usr/bin/ruby

p Array(1..6)
p Complex 6
p Float 12
p Integer "34"
p Rational 6
p String 22
</pre>

<p>
Here we show the <code>Kernel</code> conversion methods. 
</p>

<pre>
$ ./convertmethods.rb
[1, 2, 3, 4, 5, 6]
(6+0i)
12.0
34
(6/1)
"22"
</pre>

<p>
Output of the example. 
</p>


<hr class="btm">

<pre class="code">
#!/usr/bin/ruby

p "12".to_i
p 12.5.to_i
p nil.to_i

p 12.to_f
p "11".to_f
p nil.to_f
</pre>

<p>
In the above example, we show some numerical conversions. 
Some Ruby objects have <code>to_i</code> and <code>to_f</code> 
methods which convert objects to integers and floats, respectively.
</p>

<pre class="explanation">
p "12".to_i
p 12.5.to_i
p nil.to_i
</pre>

<p>
In this code we convert a string, decimal and nil to integer type.
</p>

<pre class="explanation">
p 12.to_f
p "11".to_f
p nil.to_f      
</pre>

<p>
These three lines convert an integer, string and nil to an object of
decimal data type.
</p>

<pre>
$ ./conversions.rb
12
12
0
12.0
11.0
0.0
</pre>

<p>
Example output.
</p>

<hr class="btm">

<p>
The second example shows some string conversions.
</p>


<pre class="code">
#!/usr/bin/ruby

p "12".to_i
p "13".to_f
p "12".to_r
p "13".to_c

p "Jane".to_sym

v = "Ruby Python Tcl PHP Perl".split
p v.class
</pre>

<p>
In the above example we convert strings to objects
of different data types. 
</p>

<pre class="explanation">
p "12".to_i
p "13".to_f
p "12".to_r
p "13".to_c
</pre>

<p>
Here strings are converted to integer, decimal, rational and
complex numbers. 
</p>

<pre class="explanation">
p "Jane".to_sym
</pre>

<p>
A string becomes a symbol. 
</p>

<pre class="explanation">
v = "Ruby Python Tcl PHP Perl".split
p v.class
</pre>

<p>
Here we use a <code>split</code> method of the <code>String</code>
class to convert a string to an array. 
</p>

<pre>
$ ./stringconv.rb
12
13.0
(12/1)
(13+0i)
:Jane
Array
</pre>

<p>
And this is what we get. 
</p>

<hr class="btm">

<p>
The next small example shows array hash conversions.
</p>

<pre class="code">
#!/usr/bin/ruby

h = {:de => "Germany", :sk => "Slovakia"}
p h.to_a

a = [:de, "Germany", :sk, "Slovakia", 
     :hu, "Hungary", :no, "Norway"]
p Hash[*a]
</pre>

<p>
In the example code, we create a hash and covert it
to array. Then we create an array and convert it to
a hash.
</p>

<pre class="explanation">
h = {:de => "Germany", :sk => "Slovakia"}
p h.to_a
</pre>

<p>
A hash is created and converted to an array using the 
<code>to_a</code> method.
</p>

<pre class="explanation">
a = [:de, "Germany", :sk, "Slovakia", 
     :hu, "Hungary", :no, "Norway"]
p Hash[*a]
</pre>

<p>
An array is created and converted to a hash. 
The asterix in this context is a splat operator. It
is one of a Ruby idioms taken from Perl. It splits an array
into a few variables. 
</p>

<pre>
$ ./h2a.rb
[[:de, "Germany"], [:sk, "Slovakia"]]
{:de=>"Germany", :sk=>"Slovakia", :hu=>"Hungary", :no=>"Norway"}
</pre>

<p>
Output.
</p>

<p>
In this part of the Ruby tutorial, we covered data types and their conversions.  
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified November 22, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

